package com.dokimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dokimall.auth.feign.MemberFeignService;
import com.dokimall.common.constant.AuthServerConstant;
import com.dokimall.common.vo.MemberVo;
import com.dokimall.auth.vo.SociaUser;
import com.dokimall.common.utils.HttpUtils;
import com.dokimall.common.utils.R;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 处理社交登录请求
 */

@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session,HttpServletRequest httpServletRequest) throws Exception {
        Map<String,String> map = new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id","8f478b1c760ba014e06758476b2eac9cc94a0cc808640159cdacb9df6a214179");
        map.put("redirect_uri","http://auth.dokimall.com/oauth2.0/gitee/success");
        map.put("client_secret","2fede8b5349d215ead9b650327eba7bf2f42ad3242a63bcd9a4a45cb52f29763");
        Map<String, String> headers = new HashMap<>();
        // 根据code等信息换取accessToken
        HttpResponse post = HttpUtils.doPost("https://gitee.com/", "oauth/token", "post",headers, null, map);
        if(post.getStatusLine().getStatusCode()==200){
            String string = EntityUtils.toString(post.getEntity());
            SociaUser sociaUser = JSON.parseObject(string, SociaUser.class);
            //查看用户状态（是否已注册）
            //如果是第一次进网站，自动注册
            R r = memberFeignService.socialLogin(sociaUser);
            if(r.getCode()==0){
                MemberVo data = r.getData("data", new TypeReference<MemberVo>(){});
                //1、第一次使用session，命令浏览器保存卡号。JSESSIONID这个cookie；
                //以后浏览器访问哪个网站就会带上这个网站的cookie；
                //子域之间；打卡的时候，即使是子域系统发的卡，也能让父域直接使用（配置项，也已经处理使用JSON序列化来序列化对象数据到redis中

                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                System.out.println("用户的登录信息{}"+data);
                return "redirect:http://dokimall.com";
            }
        }else{
            return "redirect:http://auth.dokimall.com/login.html";
        }
        return "redirect:http://auth.dokimall.com/login.html";
    }
}
